package com.soft.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soft.entity.SensitiveWord;
import com.soft.mapper.SensitiveWordMapper;
import com.soft.service.SensitiveWordService;

/**
 * 敏感词服务实现：维护词库、提供过滤/检测能力，并在内存中做短期缓存以提升性能。
 */
@Service
public class SensitiveWordServiceImpl implements SensitiveWordService {
    
    @Autowired
    private SensitiveWordMapper sensitiveWordMapper;
    
    // 敏感词缓存
    private volatile List<SensitiveWord> sensitiveWordsCache = new ArrayList<>();
    private volatile long lastCacheTime = 0;
    private static final long CACHE_EXPIRE_TIME = 5 * 60 * 1000; // 5分钟缓存过期
    
    @Override
    public boolean addSensitiveWord(SensitiveWord sensitiveWord) {
        // 1) 填充时间字段
        sensitiveWord.setCreateTime(LocalDateTime.now());
        sensitiveWord.setUpdateTime(LocalDateTime.now());
        // 2) 插入数据库
        boolean result = sensitiveWordMapper.insert(sensitiveWord) > 0;
        if (result) {
            // 3) 成功后刷新缓存，保证新词立刻可用
            refreshSensitiveWordsCache();
        }
        return result;
    }
    
    @Override
    public boolean deleteSensitiveWord(Integer wordId) {
    // 删除后刷新缓存
    boolean result = sensitiveWordMapper.deleteById(wordId) > 0;
        if (result) {
            refreshSensitiveWordsCache();
        }
        return result;
    }
    
    @Override
    public boolean updateSensitiveWord(SensitiveWord sensitiveWord) {
    // 更新更新时间
        sensitiveWord.setUpdateTime(LocalDateTime.now());
        boolean result = sensitiveWordMapper.updateById(sensitiveWord) > 0;
        if (result) {
            refreshSensitiveWordsCache();
        }
        return result;
    }
    
    @Override
    public SensitiveWord getSensitiveWordById(Integer wordId) {
        return sensitiveWordMapper.selectById(wordId);
    }
    
    @Override
    public List<SensitiveWord> listAllSensitiveWords() {
    // 列出全部敏感词（按创建时间倒序）
    return sensitiveWordMapper.selectList(
            new QueryWrapper<SensitiveWord>().orderByDesc("create_time")
        );
    }
    
    @Override
    public List<SensitiveWord> listActiveSensitiveWords() {
        return sensitiveWordMapper.selectActiveSensitiveWords();
    }
    

    
    @Override
    public String filterSensitiveContent(String content) {
        if (content == null || content.trim().isEmpty()) {
            return content;
        }
        
        try {
            // 1) 读取缓存词库，过期会自动刷新
            List<SensitiveWord> words = getCachedSensitiveWords();
            String result = content;
            
            // 2) 遍历启用词并做不区分大小写替换
            for (SensitiveWord word : words) {
                if ("active".equals(word.getStatus())) {
                    String pattern = Pattern.quote(word.getWord());
                    // 统一替换为 ***
                    result = result.replaceAll("(?i)" + pattern, "***");
                }
            }
            
            return result;
        } catch (Exception e) {
            // 如果敏感词服务出错，直接返回原内容，不影响评论功能
            System.err.println("敏感词过滤出错: " + e.getMessage());
            return content;
        }
    }
    
    @Override
    public boolean containsSensitiveWords(String content) {
        if (content == null || content.trim().isEmpty()) {
            return false;
        }
        
    // 使用缓存词库降低查询负载
    List<SensitiveWord> words = getCachedSensitiveWords();
        String lowerContent = content.toLowerCase();
        
        for (SensitiveWord word : words) {
            if ("active".equals(word.getStatus()) && 
                lowerContent.contains(word.getWord().toLowerCase())) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public List<String> findSensitiveWords(String content) {
        List<String> foundWords = new ArrayList<>();
        
        if (content == null || content.trim().isEmpty()) {
            return foundWords;
        }
        
    // 返回命中的词清单，便于前端标注
    List<SensitiveWord> words = getCachedSensitiveWords();
        String lowerContent = content.toLowerCase();
        
        for (SensitiveWord word : words) {
            if ("active".equals(word.getStatus()) && 
                lowerContent.contains(word.getWord().toLowerCase())) {
                foundWords.add(word.getWord());
            }
        }
        
        return foundWords;
    }
    
    /** 刷新内存缓存（主动触发） */
    @Override
    public void refreshSensitiveWordsCache() {
    // 主动刷新：从DB读取 active 词库到内存
        sensitiveWordsCache = listActiveSensitiveWords();
        lastCacheTime = System.currentTimeMillis();
    }
    
    /**
     * 获取缓存的敏感词列表
     */
    /**
     * 获取缓存的敏感词列表（过期则自动刷新）。
     */
    private List<SensitiveWord> getCachedSensitiveWords() {
        try {
            long currentTime = System.currentTimeMillis();
            
            // 如果缓存过期或为空，重新加载
            if (sensitiveWordsCache.isEmpty() || 
                (currentTime - lastCacheTime) > CACHE_EXPIRE_TIME) {
                refreshSensitiveWordsCache();
            }
            
            return sensitiveWordsCache;
        } catch (Exception e) {
            // 兜底：缓存出错也不影响功能
            System.err.println("获取敏感词缓存出错: " + e.getMessage());
            return new ArrayList<>();
        }
    }
}